<head>

    <link href="https://vjs.zencdn.net/7.2.3/video-js.css" rel="stylesheet">
    <link href="./css/subtitle.css" rel="stylesheet" media="screen" type="text/css" />
</head>

<body>
    <div id="holder">
        <div id="video-container">
            <video id="my-video" class="video-js vjs-big-play-centered" controls preload="auto" width="970" height="auto" data-setup="{}"
                autoplay="true">
                <source src="https://video.pc6.com/v/1807/dyzbzmktxinxg.mp4" type="video/mp4">
                <p class="vjs-no-js">
                    To view this video please enable JavaScript, and consider upgrading to a web browser that
                    <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a>
                </p>
            </video>
        </div>
        <div id="subtitle-container">
            <ul id="subtitle-list"></ul>
        </div>
    </div>
    <script src="https://vjs.zencdn.net/7.2.3/video.js"></script>
    <script src="js/subtitle.js"></script>
    <script>
        var ipcRenderer = require('electron').ipcRenderer;

        var holder = document.getElementById('holder');
        var subtitleList = document.getElementById("subtitle-list");
        var vid = document.getElementById("my-video");

        var subtitleIndex = 0;
        var subtitles = [];

        var replayTimeout;
        var replaying = false;

        var player = videojs("my-video");

        vid.ontimeupdate = () => {
            if (replaying || player.paused()) {
                // do nothing
            } else {
                moveSubtitle();
            }
        };

        vid.onseeked = () => {
            console.log("onseeked");
            subtitleIndex = 0;
        }

        document.onkeydown = (event) => {
            console.log("onkeypress", event);
            if (event.code === "Space") {
                if (player.paused()) {
                    player.play();
                } else {
                    player.pause();
                }
                return false;
            }
        }


        var newSettings = {
            backgroundOpacity: '0',
            edgeStyle: 'dropshadow',
            fontPercent: 1.25,
        };
        player.textTrackSettings.setDefaults();
        player.textTrackSettings.setValues(newSettings);
        player.textTrackSettings.updateDisplay();

        holder.ondragover = function () {
            return false;
        };
        holder.ondragleave = holder.ondragend = function () {
            return false;
        };
        holder.ondrop = function (e) {
            e.preventDefault();
            var file = e.dataTransfer.files[0];
            console.log('File you dragged here is', file.path);
            ipcRenderer.send('fileDrop', file.path);
            return false;
        };

        ipcRenderer.on('fileSelected', function (event, message) {
            console.log(message);
            player.on('ready', function() {
                console.log(ready);
            });
            vid.src = message;
            player.play();
        });

        ipcRenderer.on("subtitleSelected", (event, message) => {
            console.log(message);
            var tracks = player.remoteTextTracks();
            for (var i = 0; i < tracks.length; i++) {
                player.removeRemoteTextTrack(tracks[i]);
            }
            const trackEl = player.addRemoteTextTrack({ src: message, label: "English", "mode": "showing" }, true);
            parseVtt(message, (err, data) => {
                if (!err) {
                    subtitles = data;
                    renderSubtitle(subtitles);
                }
            })
        })
        ipcRenderer.send("ipcRendererReady", "true");

        function replay(begin, long) {
            replaying = true;
            player.currentTime(begin);
            player.play();
            clearTimeout(replayTimeout);
            replayTimeout = setTimeout(() => {
                player.pause();
                replaying = false;
            }, long * 1000)
        }

        function moveSubtitle() {
            var result = searchSubtitle(subtitles, subtitleIndex, vid.currentTime);
            if (result) {
                clearCurrentTitleStyle();
                subtitleIndex = result.newIndex;
                var list = subtitleList;
                var children = list.childNodes;
                var baseTop = list.firstChild.offsetTop;
                if (result.newIndex < children.length) {
                    var child = children[result.newIndex];
                    var title = child.childNodes[1];
                    title.setAttribute("class", "current-title");
                    list.scrollTop = child.offsetTop + child.offsetHeight - baseTop - list.offsetHeight;
                }
            }
        }

        function clearCurrentTitleStyle() {
            var children = subtitleList.childNodes;
            for (var i = 0; i < children.length; i++) {
                var child = children[i];
                child.childNodes[1].removeAttribute("class");
            }
        }

        function renderSubtitle(subtitles) {
            var list = subtitleList;
            while (list.hasChildNodes()) {
                list.removeChild(list.lastChild);
            }
            for (var i = 0; i < subtitles.length; i++) {
                var subtitle = subtitles[i];
                var node = document.createElement("LI");
                var text = "[" + subtitle.begin.substr(0, 8) + "]";
                var textnode = document.createElement("span");
                textnode.innerHTML = text;
                node.appendChild(textnode)
                var titleNode = document.createElement("span");
                titleNode.innerHTML = subtitle.title;
                titleNode.setAttribute("id", "title");
                node.appendChild(titleNode);
                var replayControl = document.createElement("BUTTON");
                replayControl.setAttribute("class", "replay");
                replayControl.setAttribute("data-begin", subtitle.beginTime);
                replayControl.setAttribute("data-end", subtitle.endTime);
                replayControl.innerHTML = "replay";
                replayControl.onclick = (event) => {
                    clearCurrentTitleStyle();
                    var target = event.target;
                    target.parentNode.childNodes[1].setAttribute("class", "current-title");
                    var begin = parseFloat(event.target.getAttribute("data-begin"));
                    var end = parseFloat(event.target.getAttribute("data-end"));
                    replay(begin - 2, end - begin + 3);
                }
                node.appendChild(replayControl);

                list.appendChild(node);
            }
            list.scrollTop = list.scrollHeight;
        }
    </script>
</body>